<?php

class UserController extends Controller
{
    public function init()
    {
        parent::init();
        $this->R->module = '用户管理';
    }
	public function actionIndex()
	{
		$this->render('index');
	}
    public function actionList() 
    {
        $page = $this->getParam('page');
        $rows = $this->getParam('rows');
        $criteria = new CDbCriteria();
        $criteria->order = '`ID` desc';
        $arr = array();
        $count = User::model()->count($criteria);
        $criteria->limit = $rows;
        $criteria->offset = ($page - 1) * $rows;
        $arr['total'] = $count;
        $users = User::model()->findAll($criteria);
        foreach ($users as $user)
        {
            $arr['rows'][] = $user->attributes;
        }
        if (!$count)
        {
            $arr['rows'] = array();
        }
        echo json_encode($arr);exit;
    }
    //创建或编辑管理员用户
    public function actionCreate() 
    {

        $id = $this->getParam('ID');
        if ($id)
        {
            $this->R->action = '修改用户';
            $model = User::model()->findByPk($id);
        }
        else
        {
            $this->R->action = '添加用户';
            $model = new User;
        }
        $model->Password = md5($this->getTrimParam('Password'));
        $model->Name = $this->getTrimParam('Name');
        $model->Email = $this->getTrimParam('Email');
        $model->Status = $this->getParam('Status');
        $this->R->success = $model->save()? true : false;
        $this->R->flush();
    }
        //删除用户
    public function actionDelete(){
        $id = $this->getParam('id');
        $this->R->action = '删除用户';
        $this->R->noalert = true;
        if (User::model()->deleteByPk($id))
        {
            $this->R->success = true;      
            $this->R->msg = '操作成功';
        }
        else
        {
            $this->R->success = false;
            $this->R->msg = '操作失败';
        }
        $this->R->flush();
    }
    //检查用户名是否唯一
    public function actionCheckUnique()
    {
        $name = $this->getTrimParam('Name');
        $id = $this->getParam('id');
        $model = User::model()->find('Name = :name',array(':name'=>$name));
        if ($id)
        {
            $model = User::model()->find('Name = :name AND ID !=:id',array(':name'=>$name,':id'=>$id));
        }
        if ($model == null)
        {
            echo 'true';exit;
        }
        echo 'false';exit;
    }

}